package com.cby.operation.pay.ui

import android.app.Activity
import android.content.ComponentName
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.text.Html
import android.text.TextUtils
import android.view.View
import android.widget.Button
import android.widget.TextView
import com.cby.operation.anti.AntiAddictManager
import com.cby.operation.common.ext.getDrawableId
import com.cby.operation.common.ext.getId
import com.cby.operation.common.ext.showToast
import com.cby.operation.common.ui.BaseDialogFragment
import com.cby.operation.common.util.CbyLogUtils
import com.cby.operation.common.util.StringUtils
import com.cby.operation.common.util.WebUtils
import com.cby.operation.login.LoginManager
import com.cby.operation.login.data.InternalUser
import com.cby.operation.pay.PayManager
import com.cby.operation.pay.bean.PayInfo
import com.cby.operation.pay.bean.PayLimit
import com.cby.operation.pay.bean.PayResult
import com.cby.operation.sdk.*
import com.cby.operation.sdk.util.HykbAppUtils

/**
 * Description:支付限额提醒
 *
 * @author 陈宝阳
 * @create 2020/8/14 15:58
 */
class PayLimitDialogFragment : BaseDialogFragment() {

    private lateinit var publicPolicyTv: TextView
    private lateinit var warmTipTv: TextView
    private lateinit var detailTv: TextView
    private lateinit var negativeBtn: Button
    private lateinit var positiveBtn: Button
    private lateinit var btnLineView: View
    private var payLimit: PayLimit? = null
    private var payInfo: PayInfo? = null

    override fun parseArgs() {
        payLimit = arguments.getParcelable(KEY_PAY_LIMIT)
        payInfo = arguments.getParcelable(KEY_PAY_INFO)
    }

    override fun layoutName() = "anti_dialog_fragment"

    override fun initView(view: View?) {
        view?.let {
            publicPolicyTv = view.findViewById(getId("tv_public_policy"))
            warmTipTv = view.findViewById(getId("tv_warm_tip"))
            detailTv = view.findViewById(getId("tv_detail"))
            negativeBtn = view.findViewById(getId("dlg_btn_negative"))
            positiveBtn = view.findViewById(getId("dlg_btn_positive"))
            btnLineView = view.findViewById(getId("view_btn_line"))
        }
    }

    override fun setContent() {
        payLimit?.let {
            if (it.linkInfo != null && !TextUtils.isEmpty(it.linkInfo!!.name)
                && !TextUtils.isEmpty(it.linkInfo!!.url)
            ) {
                detailTv.text = it.linkInfo!!.name
                detailTv.visibility = View.VISIBLE
            } else {
                detailTv.visibility = View.GONE
            }

            //设置文案内容
            if (!TextUtils.isEmpty(it.content)) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    publicPolicyTv.text = Html.fromHtml(
                        it.content,
                        Html.FROM_HTML_MODE_LEGACY
                    )
                } else {
                    publicPolicyTv.text = Html.fromHtml(it.content)
                }
            }

            //设置温馨提示
            if (!TextUtils.isEmpty(it.tips)) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    warmTipTv.text = Html.fromHtml(it.tips, Html.FROM_HTML_MODE_LEGACY)
                } else {
                    warmTipTv.text = Html.fromHtml(it.tips)
                }
                warmTipTv.visibility = View.VISIBLE
            } else {
                warmTipTv.visibility = View.GONE
            }

            it.buttonInfoList?.let { it2 ->
                if (it2.isNotEmpty()) {
                    negativeBtn.text = it2[0].name
                }
                if (it2.size > 1) {
                    positiveBtn.text = it2[1].name
                    positiveBtn.visibility = View.VISIBLE
                    btnLineView.visibility = View.VISIBLE
                    negativeBtn.setBackgroundResource(getDrawableId("hykb_bg_default_dialog_left_btn")
                    )
                } else {
                    positiveBtn.visibility = View.GONE
                    btnLineView.visibility = View.GONE
                    negativeBtn.setBackgroundResource(getDrawableId("hykb_bg_default_dialog_single_btn"))
                }
            }


        }
    }

    override fun initListener() {
        payLimit?.let { it2 ->
            detailTv.setOnClickListener {
                if (it2.linkInfo != null && StringUtils.isValidHttpUrl(
                        it2.linkInfo!!.url
                    )
                ) {
                    WebUtils.openUrl(activity, it2.linkInfo!!.url!!)
                }
            }
            negativeBtn.setOnClickListener {
                if (it2.buttonInfoList != null && it2.buttonInfoList!!.isNotEmpty()) {
                    handleAction(it2.buttonInfoList!![0].func!!)
                }
            }
            positiveBtn.setOnClickListener {
                if (it2.buttonInfoList != null && it2.buttonInfoList!!.size > 1) {
                    handleAction(it2.buttonInfoList!![0].func!!)
                }
            }
        }

    }

    private fun handleAction(action: String) {
        when (action) {
            ACTION_WSSFXX ->         // 完善身份信息
                openIdCardActivity()
            ACTION_EXIT_POPUP -> {
                // 关闭弹窗后
                val result = PayResult()
                result.payInfo = payInfo
                result.resultCode = CODE_PAY_LIMIT_DIALOG_CLOSE
                result.message = ERR_MSG_PAY_LIMIT_DIALOG_CLOSE
                PayManager.instance.handlePayCallBack(result)
                dismissAllowingStateLoss()
            }
            else -> {
            }
        }
    }

    /**
     * 跳转到快爆完成实名认证
     */
    private fun openIdCardActivity() {
        if (!HykbAppUtils.checkHykbSupport(activity)) {
            AntiAddictManager.instance.openRealNameWeb(activity)
        } else {
            val user: InternalUser = LoginManager.instance.getUser() ?: return
            val intent = Intent("android.intent.action.VIEW")
            intent.putExtra(KEY_UID, user.userId)
            intent.putExtra(KEY_NICK, user.nick)
            intent.putExtra(KEY_LOGIN_TYPE, user.loginType)
            intent.putExtra(KEY_APP_ID, SdkConfiguration.gameId)
            //固定字段
            intent.putExtra("key", "loginsdk")
            val componentName = ComponentName(
               HYKB_PACKAGE_NAME,
                "com.xmcy.hykb.app.ui.idcard.IdCardActivity"
            )
            intent.component = componentName
            startActivityForResult(intent, REQUEST_CODE_USER)
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (requestCode == REQUEST_CODE_USER && data != null) {
            val status: Boolean = data.getBooleanExtra("status", false)
            val msg: String? = data.getStringExtra("msg")
            CbyLogUtils.i("m3839", "status = $status, msg = $msg")
            if (!status) {
                if (!TextUtils.isEmpty(msg)) {
                    activity.showToast(msg!!)
                }
                return
            }
            val result = PayResult()
            result.payInfo = payInfo
            result.resultCode = CODE_PAY_LIMIT_DIALOG_CLOSE
            result.message = ERR_MSG_PAY_LIMIT_DIALOG_CLOSE
            PayManager.instance.handlePayCallBack(result)
            dismissAllowingStateLoss()
        }
    }

    companion object {
        private const val REQUEST_CODE_USER = 1003
        private const val KEY_PAY_LIMIT = "pay_limit"
        const val KEY_NICK = "nick"
        const val KEY_UID = "uid"
        const val KEY_LOGIN_TYPE = "platform"
        const val KEY_APP_ID = "app_id"
        fun show(activity: Activity,
            payLimit: PayLimit?,
            payInfo: PayInfo?
        ): PayLimitDialogFragment {
            val fragment = PayLimitDialogFragment()
            val data = Bundle()
            data.putParcelable(KEY_PAY_LIMIT, payLimit)
            data.putParcelable(KEY_PAY_INFO, payInfo)
            fragment.arguments = data
            fragment.show(activity.fragmentManager, TAG_FRAGMENT_PAY_LIMIT)
            return fragment
        }
    }
}